package com.lihaozhe.orderservice.controller;

import com.lihaozhe.orderservice.dto.OrderDTO;
import com.lihaozhe.orderservice.dto.OrderItemDTO;
import com.lihaozhe.orderservice.service.LoadBalancerService;
import com.lihaozhe.orderservice.util.LoadbalancerUtil;
import com.lihaozhe.productservice.dto.ProductDTO;
import com.lihaozhe.userservice.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 订单服务控制器 - 负载均衡版本
 * 演示负载均衡的各种使用方式
 *
 * @author 李昊哲
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/orders")
public class OrderController {
  private final LoadBalancerService loadBalancerService;
  private final List<OrderDTO> orders = new ArrayList<>();
  private Long orderIdCounter = 1L;
  private final Logger logger = LoggerFactory.getLogger(this.getClass());
  private final LoadbalancerUtil loadbalancerUtil;

  /**
   * 构造函数，注入服务发现工具类
   */
  public OrderController(LoadBalancerService loadBalancerService, LoadbalancerUtil loadbalancerUtil) {
    this.loadBalancerService = loadBalancerService;
    this.loadbalancerUtil = loadbalancerUtil;
  }

  /**
   * 创建订单 - 使用负载均衡版本
   * POST /api/orders
   * 演示调用用户服务和商品服务
   */
  @PostMapping
  public Map<String, Object> createOrder(@RequestBody Map<String, Object> orderRequest) {
    Long userId = Long.valueOf(orderRequest.get("userId").toString());
    Long productId = Long.valueOf(orderRequest.get("productId").toString());
    Integer quantity = Integer.valueOf(orderRequest.get("quantity").toString());

    logger.info("创建订单 - 用户ID: {}, 商品ID: {}, 数量: {}", userId, productId, quantity);

    try {
      // 1. 使用负载均衡调用用户服务
      UserDTO user = loadBalancerService.getUserWithLoadBalancer(userId);
      if (user == null) {
        return Map.of("success", false, "message", "用户不存在");
      }

      // 2. 使用负载均衡调用商品服务
      ProductDTO product = loadBalancerService.getProductWithLoadBalancer(productId);
      if (product == null) {
        return Map.of("success", false, "message", "商品不存在");
      }

      // 3. 检查库存
      if (product.getStock() < quantity) {
        return Map.of("success", false, "message", "库存不足");
      }

      // 4. 创建订单
      OrderItemDTO orderItem = new OrderItemDTO(productId, product.getName(), quantity, product.getPrice());
      List<OrderItemDTO> items = List.of(orderItem);
      Double totalAmount = product.getPrice() * quantity;

      OrderDTO order = new OrderDTO(orderIdCounter++, userId, items, totalAmount, "CREATED");
      orders.add(order);

      return Map.of(
          "success", true,
          "message", "订单创建成功",
          "orderId", order.getId(),
          "totalAmount", totalAmount,
          "user", user.getUsername(),
          "product", product.getName()
      );

    } catch (Exception e) {
      return Map.of("success", false, "message", "创建订单失败: " + e.getMessage());
    }
  }


  /**
   * 根据订单ID获取订单详情
   * GET /api/orders/{orderId}
   */
  @GetMapping("/{orderId}")
  public OrderDTO getOrder(@PathVariable("orderId") Long orderId) {
    return orders.stream()
        .filter(o -> o.getId().equals(orderId))
        .findFirst()
        .orElse(null);
  }

  /**
   * 获取用户的所有订单
   * GET /api/orders/user/{userId}
   */
  @GetMapping("/user/{userId}")
  public List<OrderDTO> getUserOrders(@PathVariable("userId") Long userId) {
    return orders.stream()
        .filter(o -> o.getUserId().equals(userId))
        .toList();
  }


  /**
   * 负载均衡测试端点
   * GET /api/orders/loadbalance-test?calls=20
   */
  @GetMapping("/loadbalance-test")
  public Map<String, Object> loadBalanceTest(@RequestParam(name = "calls", defaultValue = "20") int calls) {
    return loadBalancerService.testLoadBalancing(calls);
  }

  /**
   * GET /api/orders/testServiceInstance
   *
   * @return 商品服务地址
   */
  @GetMapping("/testServiceInstance")
  public List<String> testServiceInstance() {
    return IntStream.range(0, 10)
        .mapToObj(i -> loadbalancerUtil.getCurrentServiceUrl("product-service"))
        .collect(Collectors.toCollection(ArrayList::new));
  }

  /**
   * GET /api/orders/randomServiceInstance
   *
   * @return 随机商品服务地址
   */
  @GetMapping("/randomServiceInstance")
  public List<String> randomServiceInstance() {
    return IntStream.range(0, 10)
        .mapToObj(i -> loadbalancerUtil.randomServiceUrl("product-service"))
        .collect(Collectors.toCollection(ArrayList::new));
  }

  /**
   * 获取商品服务实例信息
   * GET /api/orders/service-instances
   */
  @GetMapping("/service-instances")
  public Map<String, Object> getServiceInstances() {
    List<ServiceInstance> instances = loadBalancerService.getProductServiceInstances();
    ServiceInstance currentInstance = loadBalancerService.getCurrentProductServiceInstance();

    List<Map<String, Object>> instanceInfo = instances.stream()
        .map(instance -> Map.of(
            "instanceId", instance.getInstanceId(),
            "host", instance.getHost(),
            "port", instance.getPort(),
            "uri", instance.getUri().toString(),
            "metadata", instance.getMetadata(),
            "isCurrent", instance.equals(currentInstance)
        )).toList();

    return Map.of(
        "serviceName", "product-service",
        "totalInstances", instances.size(),
        "currentInstance", currentInstance != null ? currentInstance.getInstanceId() : "none",
        "instances", instanceInfo
    );
  }

  /**
   * 健康检查端点
   * GET /api/orders/health
   */
  @GetMapping("/health")
  public Map<String, Object> health() {
    return Map.of(
        "status", "UP",
        "service", "order-service",
        "timestamp", System.currentTimeMillis(),
        "totalOrders", orders.size(),
        "loadBalancerEnabled", true
    );
  }
}
